package edu.hit.irlab.coref.trainer;

import java.io.IOException;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import nlpeap.ml.InstanceWriter;
import edu.hit.irlab.coref.CRTrainModel;
import edu.hit.irlab.coref.PairFeatureExtractor;
import edu.hit.irlab.coref.PairInstance;
import edu.hit.irlab.coref.mentionfinder.Mention;

/**
 * The trainer that construct instances use the method mentioned
 * in [Soon. 2001]
 * 
 * @author chuter
 *
 */
public class SoonTrainer extends CorfTrainer {
	public static Log _log = LogFactory.getLog(CRTrainModel.class.getName());
	public SoonTrainer(List<PairFeatureExtractor> fes, InstanceWriter iw) 
		throws IOException 
	{ super(fes, iw); }

	/** construct instances and write into file 
	 * @throws IOException */
	public void train(Mention[] mention_arr) throws IOException
	{
		int i;
        int j;
        for (i = 1; i < mention_arr.length; i++) {
            Mention m_i = mention_arr[i];
            for (j = i-1; j >= 0; j--) {
                Mention m_j = mention_arr[j];
                if (m_i.isCoreferent(m_j)) {
                    // hooray, found a pair
                    // we only generate negative instances iff
                    // they occur between two positive instances
                    // i.e. not if they occur with a discourse-new mention
                    for (int k = i-1; k >= j; k--) {
                        Mention m_k = mention_arr[k];
                        if (m_i.overlapsWith(m_k) || m_i.embeds(m_k))
                        	continue;
                        PairInstance inst = new PairInstance(m_i, m_k);
                        for (PairFeatureExtractor fe: _fes) {
                            fe.extractFeatures(inst);
                        }
                        boolean posInst = m_i.isCoreferent(m_k);
                        _log.info(String.format("\nthe instance is (%s) :%s--:--%s"
                        		, posInst, m_i, m_k));
                        inst.setFeature(PairInstance.FD_POSITIVE, posInst);
                        _iw.write(inst);
                    }
                    break;
                }
            }
        }
        _iw.flush();
	}

}
